<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		
		
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
		</style>
		<!--<style type="text/css">
			#myCanvas{
				
				border: 2px solid firebrick;
				display: block;
				margin: 0 auto;
			}
		</style>-->
	</head>
	<body>
		
		
		<canvas id="myCanvas" width="500" height="500"  style="width:100%;height:100%;"></canvas>
		
		<script type="text/javascript">
			
			var canvas=document.getElementById('myCanvas');
			var context=canvas.getContext('2d');
			//context.beginPath();
			//面向对象的思想去创建对象，以及小球的移动方式
			function ranNum(m,n){
				var ran=Math.floor(Math.random()*(n-m+1)+m);
				return ran;
				
			}
			//console.log(ranNum(5,10));
			function Ball(){
				//设置属性
				this.r=ranNum(5,30);
				this.color='rgb('+ranNum(0,255)+','+ranNum(0,255)+','+ranNum(0,255)+')';
				this.x=ranNum(this.r,canvas.width-this.r);
				this.y=ranNum(this.r,canvas.height-this.r);
				//随机一个水平方向上的速度
				this.speedX=ranNum(2,10)*(ranNum(0,1)?1:-1);
				//随机一个垂直方向上的速度
				this.speedY=ranNum(2,10)*(ranNum(0,1)?1:-1);
				
				
				
			}
			Ball.prototype.move=function(){
				this.x+=this.speedX;
				this.y+=this.speedY;
				
				if(this.x<=this.r){
					this.x=this.r;
					this.speedX*=-1;
					
					
				}
				if(this.x>=canvas.width-this.r){
					this.x=canvas.width-this.r;
					this.speedX*=-1;
					
				}
				
				if(this.y<=this.r){
					this.y=this.r;
					this.speedY*=-1;
				}
				if(this.y>=canvas.height-this.r){
					this.y=canvas.height-this.r;
					this.speedY*=-1;
					
				}
				
			}
			//绘制小球
		   Ball.prototype.draw=function(){
		   	context.beginPath();
		   	context.arc(this.x,this.y,this.r,0,Math.PI*2,false);
		   	context.fillStyle=this.color;
		   	context.fill();
		   	
		   	
		   }
			
			//创建小球对象
			//用数组存储所有的球
			var balls=[];
			for(var i=0;i<20;i++){
				var ball= new Ball();
				ball.draw();
				balls.push(ball);
			}
			setInterval(function(){
				context.clearRect(0,0,canvas.width,canvas.height);
				for(var i=0;i<balls.length;i++){
								balls[i].draw();
								balls[i].move();
			}
			},200)
			

			
			
			
			
			
					</script>
	</body>
</html>
